package cn.edu.cqupt.controller;

import cn.edu.cqupt.exception.ThrowingException;
import cn.edu.cqupt.po.Picture;
import cn.edu.cqupt.service.PictureService;
import cn.edu.cqupt.until.ListResult;
import cn.edu.cqupt.until.Result;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author Andrew
 * @date 2018/1/15
 *
 */
@PropertySource("classpath:conf/druid.properties")//配置信息较多时应单独文件
@CrossOrigin(origins = "*")
@Controller
public class UploadController {
    private final static Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
    public static String ROOT_PATH ;
    @Value("${picture.root.path}")
    public void setRootPath(String rootPath) {
        UploadController.ROOT_PATH = rootPath;
        System.out.println(ROOT_PATH);
    }
    @Autowired
    PictureService pictureService;

    /**
     * 图片上传
     * @param multiRequest
     * @return
     */
    @RequestMapping(value = "upload/picture", produces = "application/json;charset=UTF-8",consumes = "multipart/form-data" ,method = RequestMethod.POST)
    @ResponseBody
    public String uploadPicture(MultipartHttpServletRequest multiRequest){
        List<Integer> pictureList = new ArrayList<>();

        Iterator<String> filesNames = multiRequest.getFileNames(); //获得所有的文件名
        while(filesNames.hasNext()){    //迭代，对单个文件进行操作
            String fileName =filesNames.next();
            MultipartFile file =  multiRequest.getFile(fileName);
            if(!file.isEmpty()){
                LOGGER.debug("Process file: {}", file.getOriginalFilename());
                String filePath = System.currentTimeMillis() + file.getOriginalFilename();
                try {
                    file.transferTo(new File(ROOT_PATH ,filePath));
                } catch (IOException e) {
                    LOGGER.warn("a error with upload picture:",e);
                    return Result.failed("500","文件上传错误").toJSONString();
                }
                Picture picture = new Picture();
                picture.setPicturePath(filePath);
                pictureService.savePicture(picture);
                pictureList.add(picture.getId());
            }

        }
        return ListResult.success(pictureList).toJSONString();
    }

    /**
     * 显示图片
     * @param id 图片id
     * @param request
     * @param response
     * @return 图片资源
     */
    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadFile(@PathVariable("id")int id,
                               HttpServletRequest request, HttpServletResponse response) {
        if (id != 0) {
            Picture picture = pictureService.getPicture(id);
            return downloadFile(picture.getPicturePath(),request,response);
        }
        return null;
    }

    /**
     * 图片显示
     * @param name 图片名称
     * @param request
     * @param response
     * @return 图片资源
     */
    @RequestMapping(value = "download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadFile(@RequestParam("name") String name,
                                               HttpServletRequest request, HttpServletResponse response) {
        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.maxAge(5L, TimeUnit.SECONDS).getHeaderValue());
        File file = new File(ROOT_PATH, name);
        if (file.exists()) {
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            try(InputStream in = new FileInputStream(file)){
                byte[] media = IOUtils.toByteArray(in);
                return new ResponseEntity<>(media,headers, HttpStatus.OK);
            } catch (Exception e) {
                throw new ThrowingException("图片不存在");
            }
        }
        return null;
    }

    /**
     * 删除图片
     * @param id 图片id
     * @return
     */
    @RequestMapping(value = "/delete/picture/{id}", method = RequestMethod.POST)
    @ResponseBody
    public String removeFile(@PathVariable("id")int id) {
       boolean success = pictureService.removePicture(id);
        return Result.create(success).toJSONString();
    }
}
